package ai.service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

/**
 * 极简内存“向量库”占位实现：
 * - 仅存储文本片段，基于关键词命中次数进行朴素检索
 * - 避免外部依赖，满足简化需求
 */
public class InMemoryVectorStore {

    private final List<String> corpus = new ArrayList<>();

    public void add(String text) {
        if (text == null || text.isBlank()) return;
        corpus.add(text);
    }

    public void addAll(List<String> texts) {
        if (texts == null) return;
        for (String t : texts) {
            add(t);
        }
    }

    public String retrieve(String query, int maxChars) {
        if (corpus.isEmpty() || query == null || query.isBlank()) return "";
        String q = query.toLowerCase(Locale.ROOT);
        record Scored(String content, int score) {}

        List<Scored> scored = new ArrayList<>();
        for (String doc : corpus) {
            int s = score(doc, q);
            if (s > 0) scored.add(new Scored(doc, s));
        }
        if (scored.isEmpty()) return "";
        scored.sort(Comparator.comparingInt(Scored::score).reversed());

        StringBuilder sb = new StringBuilder();
        for (Scored s : scored) {
            if (sb.length() > 0) sb.append("\n\n---\n\n");
            sb.append(s.content());
            if (sb.length() >= maxChars) break;
        }
        if (sb.length() > maxChars) {
            return sb.substring(0, Math.max(0, maxChars));
        }
        return sb.toString();
    }

    private int score(String doc, String q) {
        String lc = Objects.requireNonNullElse(doc, "").toLowerCase(Locale.ROOT);
        int hits = 0;
        for (String token : q.split("\\s+")) {
            if (token.isBlank()) continue;
            int idx = -1;
            while ((idx = lc.indexOf(token, idx + 1)) >= 0) {
                hits++;
            }
        }
        return hits;
    }
}


